package servlets;

import hibernatelogic.HibItems;
import hibernatelogic.HibUsers;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import orm.Items;

@WebServlet("/add-new-item")
public class AddItemServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger loggerAddItemServlet = Logger.getLogger(AddItemServlet.class);
       
    public AddItemServlet() {
        super();
    }
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession sess = request.getSession();
		
		if(((String) sess.getAttribute("UserRole")).equals("2")){
			
			HibItems hibItems = new HibItems();
			Items item = new Items();
			
			String itemName = request.getParameter("nname");
			int itemPrice = Integer.parseInt(request.getParameter("nprice"));
			
			item.setItem_name(itemName);
			item.setItem_price(itemPrice);
			
			try {
				hibItems.addItem(item);
			} catch (SQLException e) {
				loggerAddItemServlet.error("Something wrong at AddItemServlet", e);
			} finally {
				hibItems = null;
				item = null;
				response.sendRedirect("/my-pet-project-0/MAddItem.jsp");
			}
			
		} else {
			response.sendError(response.SC_FORBIDDEN);
		}
	}

}
